package com.hhw.localsocketsample.service;

import android.net.Credentials;
import android.net.LocalServerSocket;
import android.net.LocalSocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LocalService {

    private final String mConnectAddress;
    private final List<LocalServiceAccept> mListSocket = new ArrayList<>();
    private boolean isClose = true;
    private LocalServerSocket mSocketServer = null;

    public LocalService(String address){
        this.mConnectAddress = address;
    }

    public void accept(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mSocketServer = new LocalServerSocket(mConnectAddress);
                    isClose  = false;
                    do{
                        System.out.println("service accept");
                        LocalSocket client = mSocketServer.accept();//堵塞,等待客户端连接

                        //获取客户端的信息
                        Credentials cre = client.getPeerCredentials();
                        int gid = cre.getGid();
                        int uid = cre.getUid();
                        int pid = cre.getPid();

                        System.out.println("pid = "+pid+
                                ";gid = "+gid+
                                "客户端已连接！");
                        mListSocket.add(new LocalServiceAccept(client));
                    }while (!isClose);

                } catch (IOException e) {
                    e.printStackTrace();
                    close();
                }
            }
        }).start();
    }

    public void send(byte[] data){
        for (LocalServiceAccept s:mListSocket){
            try {
                s.send(data);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public boolean isClose(){
        return isClose;
    }
    
    public void close(){
        isClose = true;
        
        for (LocalServiceAccept s:mListSocket){
            try {
                s.close(null);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        
        try {
            mSocketServer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
